package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.DrugInfoAdapter;
import com.glory.hikvisionmobile.adapter.IQPCListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.TrackIn.TrackInLoadBean;
import com.glory.hikvisionmobile.bean.TrackIn.XPdaEquipment;
import com.glory.hikvisionmobile.bean.from.FromStepBean;
import com.glory.hikvisionmobile.bean.from.FromStepListBean;
import com.glory.hikvisionmobile.bean.from.IQPCRecordBean;
import com.glory.hikvisionmobile.bean.from.StepBean;
import com.glory.hikvisionmobile.bean.from.StepListBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class From_IQPCRecordActivity extends BaseActivity {


    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvName_Desc)
    TextView tvNameDesc;
    @BindView(R.id.tvLotNum)
    TextView tvLotNum;
    @BindView(R.id.etTestMan)
    FreeUI_ClearEditText etTestMan;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.ivStepListArrow)
    ImageView ivStepListArrow;
    @BindView(R.id.flStepList)
    FrameLayout flStepList;
    @BindView(R.id.etRemarks)
    FreeUI_ClearEditText etRemarks;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvProjectTestList)
    RecyclerView rvProjectTestList;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.nsScroll)
    NestedScrollView nsScroll;
    @BindView(R.id.llSubmitLayout)
    LinearLayout llSubmitLayout;
    private List<String> stepList = new ArrayList<>();
    private FreeUI_GeneralPop stepPop;
    private IQPCRecordBean iqpcRecordBean;
    private IQPCListAdapter iqpcListAdapter;
    private String partName;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_from_iqpcrecord;
    }

    @Override
    protected void initView() {
        initListTitle();
        rvProjectTestList.setLayoutManager(new LinearLayoutManager(From_IQPCRecordActivity.this));
        rvProjectTestList.setItemAnimator(new DefaultItemAnimator());
        rvProjectTestList.addItemDecoration(new DividerItemDecoration(From_IQPCRecordActivity.this, 1));
        iqpcListAdapter = new IQPCListAdapter(null);
        iqpcListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        iqpcListAdapter.isFirstOnly(true);
        rvProjectTestList.setAdapter(iqpcListAdapter);
        Bundle bundle = getIntent().getExtras();
        iqpcRecordBean = (IQPCRecordBean) bundle.getSerializable("IQPCRecordBean");
        if (iqpcRecordBean != null) {
            llSubmitLayout.setVisibility(View.GONE);
            tvStep.setText(iqpcRecordBean.getStepName());
            flStepList.setEnabled(false);
            etLot.setText(iqpcRecordBean.getLotId());
            etLot.setEnabled(false);
            etTestMan.setText(iqpcRecordBean.getSendPerson());
            etTestMan.setEnabled(false);
            tvTime.setText(iqpcRecordBean.getCreated());
            tvNameDesc.setText(iqpcRecordBean.getPartName() + "/" + iqpcRecordBean.getPartDesc());
            tvLotNum.setText(iqpcRecordBean.getMainQty());
            etRemarks.setText(iqpcRecordBean.getComments());
            etRemarks.setEnabled(false);
            iqpcListAdapter.setNewData(iqpcRecordBean.getxPdaFormQrLines2());
            iqpcListAdapter.setEnable(false);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(0,0,0,0);
            nsScroll.setLayoutParams(layoutParams);
        } else {
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(0,0,0,80);
            nsScroll.setLayoutParams(layoutParams);
            try {
                tvTime.setText(FreeApi_DateUtils.longToString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            initEdit(etLot, s -> requestLotInfo(s));
        }
    }

    private void initListTitle() {
        listTv1.setText("检验项目");
        listTv2.setText("检验方法");
        listTv3.setText("抽样比例");
        listTv4.setText("检查结果");
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.VISIBLE);
    }

    private void requestLotInfo(String lotNum) {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "Check");
        map.addProperty("lotId", lotNum);

        NetUtils.requestDara("HIK.PdaTrackInLoad", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<TrackInLoadBean>>(
                new TypeToken<BaseResponseBean<TrackInLoadBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<TrackInLoadBean>> response) {
                super.onSuccess(response);

                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    TrackInLoadBean body = response.body().getBody();
                    tvNameDesc.setText(body.getPartName() + "/" + body.getPartDesc());
                    partName = body.getPartName().split("\\.")[0];
                    tvLotNum.setText(body.getMainQty());
                    if (!FreeApi_StringUtils.isEmpty(body.getCurrentStepName())) {
                        tvStep.setText(body.getCurrentStepName());
                        requestListInfo(body.getCurrentStepName());
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<TrackInLoadBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaTrackInLoad");

            }
        });
    }

    private void requestListInfo(String currentStepName) {
        JsonObject map = new JsonObject();
        map.addProperty("stepName",currentStepName);
        map.addProperty("partName",partName);
        NetUtils.requestDara("HIK.PdaFormStepItems",this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<FromStepListBean>>
                (new TypeToken<BaseResponseBean<FromStepListBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<FromStepListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                     iqpcListAdapter.setNewData(response.body().getBody().getXPdaFormQrStepItems());
                }else {
                    iqpcListAdapter.getData().clear();
                    iqpcListAdapter.setNewData(null);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<FromStepListBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaBaseLocation");
            }
        });
    }

    @Override
    protected void initData() {
        NetUtils.requestDara("HIK.PdaPrdStep", this, null, new FreeUI_DialogEntityCallBack<BaseResponseBean<StepListBean>>
                (new TypeToken<BaseResponseBean<StepListBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<StepListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    stepList.clear();
                    List<StepBean> stepBeans = response.body().getBody().getxPdaPrdSteps();
                    for (StepBean bean : stepBeans) {
                        stepList.add(bean.getName() + "/" + bean.getDescription());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<StepListBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaBaseLocation");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("品质检验记录表");
        freeUI_titleView.setRightListener("取消", v -> {
            if (iqpcRecordBean != null) {
                return;
            }

            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    tvStep.setText("");
                    etLot.setText("");
                    stepList.clear();
                    tvNameDesc.setText("");
                    etTestMan.setText("");
                    etRemarks.setText("");
                    tvLotNum.setText("");
                    iqpcListAdapter.getData().clear();
                    iqpcListAdapter.setNewData(null);
                    initData();
                }
            });

        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    private void submit() {
        String testMan = etTestMan.getText().toString().trim();
        String lot = etLot.getText().toString().trim();
        String step = tvStep.getText().toString().trim();
        String nameDesc = tvNameDesc.getText().toString().trim();
        if (FreeApi_StringUtils.isEmpty(step)) {
            showToast("请选择工序名称", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(nameDesc)) {
            showToast("名称/描述不能为空", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(testMan)) {
            showToast("请输入送检人", false);
            etTestMan.setText("");
            etTestMan.requestFocus();
            return;
        }

        if (FreeApi_StringUtils.isEmpty(lot)) {
            showToast("请输入生产批号", false);
            etLot.setText("");
            etLot.requestFocus();
            return;
        }

        DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, new DialogUtils.signCallback() {
            @Override
            public void onSignSuccess() {
                JsonObject map = new JsonObject();
                List<FromStepBean> data = iqpcListAdapter.getData();
                FromStepListBean bean = new FromStepListBean(data);
                IQPCRecordBean iqpcRecordBean = new IQPCRecordBean(lot,step,nameDesc.split("/")[1],testMan,nameDesc.split("/")[0],
                        tvTime.getText().toString(),etRemarks.getText().toString().trim(),bean,tvLotNum.getText().toString().trim());
//                IQPCRecordBean bean = new IQPCRecordBean(step, projectTest, projectProcess, methodTest, reviewTest, product, lot, testMan, result);
                map.addProperty("actionType", "save");
                map.addProperty("formType", "IPQC");
                map.add("xPdaFormQr", new JsonParser().parse(new Gson().toJson(iqpcRecordBean)).getAsJsonObject());
                NetUtils.requestDara("HIK.PdaForm", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>
                        (new TypeToken<BaseResponseBean<?>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<?>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            showConfirmDialog(From_IQPCRecordActivity.this, "提交成功");
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<?>> response) {
                        super.onError(response);
                        loadError(response.getException(), "HIK.PdaForm");
                    }
                });
            }
        }, getSupportFragmentManager());
    }

    @OnClick({R.id.flStepList, R.id.tvReplay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flStepList:
                if (stepList.size() <= 0) {
                    showToast("未获取到工序列表，请刷新后重试", false);
                    return;
                }

                if (stepPop != null) {
                    if (stepPop.isShowing()) {
                        stepPop.dismiss();
                    }
                } else {
                    stepPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flStepList.getWidth(), stepList, ivStepListArrow, (code, i) -> {
                        String[] steps = code.split("/");
                        tvStep.setText(steps[0]);
                        requestListInfo(steps[0]);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivStepListArrow);
                stepPop.showAsDropDown(flStepList, 0, 0);
                break;
            case R.id.tvReplay:

                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {

                        submit();
                    }
                });

                break;
        }
    }
}
